/* ParentBehavior.cpp - implementation of ParentBehavior class */



#include "ParentBehavior.h"

void ParentBehavior::Execute()
{
	DEBUG_PRINT("Parent Behavior(%p) %s executes\n", this,name.c_str());
	bool success = false;
    if(control->Finished())
    {
		//Moving through sequence.  If we get to end, bail.
		DEBUG_PRINT("Parent Behavior(%p) %s is finished.\n", this, name.c_str());
        return;
    }
	DEBUG_PRINT("Parent Behavior(%p) %s executes 1\n", this,name.c_str());
    if(control->GetCurrentBehavior() == NULL)
    {
        // If there is a null task, we've done something wrong
		DEBUG_PRINT("Parent Behavior(%p) %s trys to do a null behavior.\n", this, name.c_str());
        return;
	}
	DEBUG_PRINT("Parent Behavior(%p) %s executes current behavior(%p) %s 2\n", this,name.c_str(),control->GetCurrentBehavior(), control->GetCurrentBehavior()->GetName().c_str());
    // If we do have a curTask...
	
    if( !control->GetCurrentBehavior()->GetControl()->Started())
    {
		success = (control->GetCurrentBehaviorPos() > 0 ) ? true : control->GetCurrentBehavior()->CheckConditions();
		if (!success)
		{
			BehaviorFailed();
			//return;
		}
		else
		{
			// ... and it's not started yet, start it.
			DEBUG_PRINT("Parent Behavior(%p) %s starting Behavior(%p).\n",this, name.c_str(),control->GetCurrentBehavior());
			control->GetCurrentBehavior()->GetControl()->SafeEnter();
		}
    }               
    else if(control->GetCurrentBehavior()->GetControl()->Finished())
    {
        // ... and it's finished, end it properly.
		DEBUG_PRINT("Parent Behavior(%p) %s exiting Behavior(%p).\n",this, name.c_str(), control->GetCurrentBehavior());
        control->GetCurrentBehavior()->GetControl()->SafeExit();
        
        if(control->GetCurrentBehavior()->GetControl()->Succeeded())
        {
			DEBUG_PRINT("Parent Behavior(%p) %s calling BehaviorSucceeded for Behavior(%p).\n",this, name.c_str(), control->GetCurrentBehavior());
			BehaviorSucceeded();
        }
        if(control->GetCurrentBehavior()->GetControl()->Failed())
        {
			DEBUG_PRINT("Parent Behavior(%p) %s calling BehaviorFailed for Behavior(%p).\n",this, name.c_str(), control->GetCurrentBehavior());
			BehaviorFailed();
        }
    }
    else
    {               
        // ... and it's ready, update it.
		DEBUG_PRINT("Parent Behavior(%p) %s executing Behavior(%p).\n",this, name.c_str(), control->GetCurrentBehavior());
        control->GetCurrentBehavior()->Execute();
    } 
	DEBUG_PRINT("Parent Behavior(%p) %s executes 3\n", this,name.c_str());
}

void ParentBehavior::Enter() 
{
	DEBUG_PRINT("Parent Behavior(%p) %s entering and current behavior(%p).\n", this,  name.c_str(), control->GetCurrentBehavior());
    control->SetCurrent( 0 );
    if(control->GetCurrentBehavior() == NULL)
    {
         //No behavior for this control.  Shouldn't happen.
    }
}